﻿using UnityEngine;
using System.Collections;

public class SnapToOb : MonoBehaviour {

	public string[] target_tags;
	public float snap_distance = 1f;
	public float move_speed = 0.1f;
	
	private GameObject target;
	private float dist_to_closest;
	
	public bool hurt_player = false;
	public float hurt_delay = 3.0f;
	public GameObject hurt_fx;
	
	public PlayerHealth hp_system;

	void Start()
	{
		hp_system = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>();
	}
	GameObject FindOb()
	{
		foreach(string tag in target_tags)
		{
			GameObject t = FindClosestWithTag(tag);
			
			if(dist_to_closest <= snap_distance)
				return t;
		}
		
		return null;
	}
	void Move()
	{
		Vector3 dir = target.transform.position - transform.position;
		dir.Normalize();
		rigidbody2D.AddForce(dir*move_speed*Time.deltaTime);
	}
	
	// Update is called once per frame
	void Update () {
	
		GameObject ob = FindOb();
		
		
		
		if(target == null)
			target = FindOb();
		else
		{
			Move();
			
			if(hurt_player)
			{
				hurt_delay-=Time.deltaTime;
				
				
				
				if(hurt_delay <= 0f)
				{
					if(hurt_fx != null)
					{
						GameObject explosion = Instantiate(hurt_fx,transform.position,transform.rotation)as GameObject;
						Destroy (explosion,explosion.particleSystem.startLifetime);
					}
					
					float dist = Vector3.Distance(transform.position, target.transform.position);
					if(dist < 3f)
					{
						float f = (5f/(1f+dist))*2f;
						PlayerHealth.hp-=f;
					}
					
					Destroy(gameObject);
				}
				else
				{
					particleSystem.startColor = new Color(0.5f/hurt_delay,(0.5f/hurt_delay)-0.7f,(0.5f/hurt_delay)-0.7f);
				}
			}
		}
		
	
	}
	
	
	GameObject FindClosestWithTag(string tag)
	{
		GameObject[] objs = GameObject.FindGameObjectsWithTag (tag);
		GameObject closest = null;
		
		float dist = Mathf.Infinity;
		
		foreach (GameObject obj in objs)
		{
			if(obj.transform!=transform)
			{
				float dist2 = Vector3.Distance(transform.position, obj.transform.position);
				
				dist2 -= (transform.localScale.x+obj.transform.localScale.x)/2f;
				
				
				if(dist2<dist)
				{
					dist=dist2;
					closest = obj;
				}
			}
		}
		
		
		dist_to_closest = dist;
		
		if(dist_to_closest > snap_distance)
			return null;
		
		return closest;
		
	}
}
